#!/usr/bin/env python
from tempfile import mkstemp
from shutil import move
from os import remove, close
from os import system
def replace(file_path, pattern, subst, count):
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(file_path)
    for line in old_file:
        new_file.write(line.replace(pattern, subst, count))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

#import fileinput
#import sys
#def replaceAll(file,searchExp,replaceExp,count):
#    for line in fileinput.input(file, inplace=1):
#        if searchExp in line:
#            line = line.replace(searchExp,replaceExp,count)
#        sys.stdout.write(line)

def printUsage():
    print ("Usage: myCppDir [path]")



import os
def genCT(path):
  if path == '':
    path = '.'


  #store current working directory
  parentDir = os.getcwd()
  #change to target path
  os.chdir(path)

  #clean legacy temp files
  if os.path.exists("tags"):
    os.remove("tags")

  print("\n")
  print("--->generate subdir tags database under "+os.getcwd())
  #generate all subdir tags under current directory first
  #alias localtags "find * -type d -exec subdirtags.sh {} \;"
  tagslocal = "find * -type d -exec subdirtags.sh {} \;"
  os.system(tagslocal)
  #then generate global tags for current directory
  #alias globaltags "ctags --file-scope=no -R"
  print("--->generate global tags database under "+os.getcwd())
  print("\n")
  os.system("ctags  -f tags -F -h .h.H.hh.hpp.h++ --fields=+imnlSfkst  --file-scope=no -R  --totals=yes ")
  #back to original directory to continue next round operation
  os.chdir(parentDir)

def main(argv):
  """
  if current folder is the only path you want to generate tags and cscope.out, then no args are expected
  if subfolders are provided as args, then current folder is not expected. otherwise will result duplicate tags and cscope.out data entries
  """
  if argv == []:
    path = '.'
    genCT(path)
  else:
    for path in argv :
      if path == '.':
        continue
      genCT(path)

  #try:
  #  path= argv[0]
  #  print("print from main",path)
  #  genCT(path)
  #except:
  #  printUsage()



if __name__ == "__main__":
  import sys
  main(sys.argv[1:]) ## sends all but the scriptname as argument
